<script setup lang="ts">
import {
  SyncOutlined,
} from '@ant-design/icons-vue'
import type { TableProps } from 'ant-design-vue'
import PermissionMenuTree from '~/pages/setting/components/permission-menu-tree.vue'
import type { ComponentResp } from '~/api/setting/model/component.ts'
import { CommTableSize } from '~/components/comm-table/comm-table-data.ts'
import { ApiModalTableColumns } from '~/pages/setting/datas/permission-data.ts'
import type { MenuResp } from '~/api/setting/model/menu.ts'
import {
  bindPermissionApiRelationApi,
  unBindPermissionApiRelationApi,
} from '~/api/setting/permission.ts'
import { queryApiCheckedListByMenuIdOfPermissionIdApi } from '~/api/setting/api.ts'
import type { ApiReq, ApiResp } from '~/api/setting/model/api.ts'
import type { PermissionApiReq } from '~/api/setting/model/permission-api.ts'

const props = defineProps({
  permissionData: Object,
})

const emits = defineEmits(['onAuthSuccess'])

const message = useMessage()

const tableSize = shallowRef<string[]>(CommTableSize)

const columns = ApiModalTableColumns
const loading = shallowRef(false)

const dataSource = shallowRef<ApiResp[]>([])

type Key = string | number
const apiSelectedRowKeys = shallowRef<Key[]>([])

const menuResp = shallowRef<MenuResp>({})

const formQuery = reactive<ApiReq>({
  apiTitleByLike: undefined,
})

async function init() {
  if (loading.value) {
    return
  }
  loading.value = true
  try {
    const apiReq: ApiReq = {
      permissionId: props.permissionData?.id,
      menuId: menuResp.value.id,
      apiTitleByLike: formQuery.apiTitleByLike,
    }
    dataSource.value = await queryApiCheckedListByMenuIdOfPermissionIdApi(apiReq)

    apiSelectedRowKeys.value = []
    if (dataSource.value && dataSource.value.length > 0) {
      for (const permissionResp of dataSource.value) {
        if (permissionResp.checked && permissionResp.id) {
          apiSelectedRowKeys.value.push(permissionResp.id)
        }
      }
    }
  } catch (e) {
    console.log(e)
  } finally {
    loading.value = false
  }
}

function onItemSelect(selected, node) {
  if (selected) {
    menuResp.value = node
    init()
  } else {
    dataSource.value = []
  }
}

async function onSearch() {
  await init()
}

function onTableRowSelect(record: ComponentResp, selected) {
  console.log('onTableRowSelect: ', selected)
  if (selected) {
    authApi(record)
  } else {
    unAuthApi(record)
  }
}

function onTableRowChange(selectedRowKeys: Key[]) {
  apiSelectedRowKeys.value = selectedRowKeys
}

async function onClose() {
  emits('onAuthSuccess')
}

/**
 * 授权功能
 *
 * @param apiResp
 */
async function authApi(apiResp: ApiResp) {
  const close = message.loading('授权中......')
  try {
    const permissionApiReq: PermissionApiReq = {
      permissionId: props?.permissionData?.id,
      menuId: menuResp.value.id,
      apiId: apiResp.id,
    }
    const isAuth = await bindPermissionApiRelationApi(permissionApiReq)
    if (isAuth) {
      message.success('授权成功')
      await init()
    }
  } catch (e) {
    console.log(e)
  } finally {
    close()
  }
}

/**
 * 解除授权功能
 *
 * @param apiResp
 */
async function unAuthApi(apiResp: ApiResp) {
  const close = message.loading('取消授权中......')
  try {
    const permissionApiReq: PermissionApiReq = {
      permissionId: props?.permissionData?.id,
      menuId: menuResp.value.id,
      apiId: apiResp.id,
    }
    const isAuth = await unBindPermissionApiRelationApi(permissionApiReq)
    if (isAuth) {
      message.success('授权取消成功')
      await init()
    }
  } catch (e) {
    console.log(e)
  } finally {
    close()
  }
}

onMounted(() => {

})
</script>

<template>
  <a-modal
    title="授权接口"
    width="1400px"
    footer=""
    @close="onClose"
  >
    <a-space direction="vertical" size="large" class="w-full">
      <a-row :gutter="24">
        <a-col :span="6">
          <PermissionMenuTree :permission-data="props.permissionData" @on-item-select="onItemSelect" />
        </a-col>
        <a-col :span="18">
          <a-card title="接口列表" class="component-card">
            <a-input-search
              v-model:value="formQuery.apiTitleByLike"
              placeholder="请输入接口名称"
              enter-button="搜索"
              class="input-search"
              @search="onSearch"
            />
            <a-table
              :row-selection="{ selectedRowKeys: apiSelectedRowKeys,
                                onChange: onTableRowChange,
                                onSelect: onTableRowSelect,
                                getCheckboxProps: (record: ApiResp) => ({
                                  // Column configuration not to be checked
                                  disabled: record.stateId === 0 && !record.checked,
                                }) }"
              :loading="loading"
              row-key="id"
              :columns="columns"
              :data-source="dataSource"
              :size="tableSize[0] as TableProps['size']"
            >
              <template #bodyCell="scope">
                <template v-if="scope?.column?.dataIndex === 'indexNo'">
                  {{ scope?.index + 1 }}
                </template>
                <template v-if="scope?.column?.dataIndex === 'apiUrl'">
                  <a-tag class="processing-tag" color="processing">
                    <template #icon>
                      <SyncOutlined :spin="true" />
                    </template>
                    {{ scope?.record?.apiHttpMethod }}
                  </a-tag>
                  {{ scope?.record?.apiUrl }}
                </template>
                <template v-if="scope?.column?.dataIndex === 'apiTitle'">
                  <a-tag :color="scope?.record?.stateId === 1 ? 'green' : 'red'">
                    {{ scope?.record?.stateId === 1 ? '有效' : '无效' }}
                  </a-tag>
                  {{ scope?.record?.apiTitle }}
                </template>
              </template>
            </a-table>
          </a-card>
        </a-col>
      </a-row>
    </a-space>
  </a-modal>
</template>

<style scoped lang="less">
  .component-card {
    min-height: 480px;
  }
  .input-search {
    margin-bottom: 16px;
    width: 300px;
  }
  .processing-tag {
    width: 72px;
  }
</style>
